#include "main.h"

//LED
uchar led_code;

//SEG
uchar seg_pos;
uchar seg_str[12];
uchar seg_buf[8];
uchar seg_mode;

//KEY
uchar key_old;

//TIMER
ulong timer_count;

//PWM
uint pwm_count;
uint pwm_rate;
uint pwm_rate_led;

bit pwm_adj;

//============LED==============
void led_proc() {
	if(timer_count%30) return;
	
	if(~pwm_adj) {
		if(++pwm_rate_led == 100)
			pwm_adj = 1;
	} else {
		if(--pwm_rate_led == 0)
			pwm_adj = 0;
	}
	
}

//============SEG==============
void seg_proc() {
	if(timer_count%50) return;
	
	
	switch(seg_mode) {
		case 0: 
			pwm_rate ? sprintf(seg_str, "L %2d", (uint)pwm_rate):
					   sprintf(seg_str, "OFF");
		break;
		case 1:
			sprintf(seg_str, "L    %3d", (uint)pwm_rate_led);
	}
	
	seg_tran(seg_str, seg_buf);
}

//============KEY==============
void key_proc() {
	uchar key_val, key_down, key_up;
	if(timer_count%10) return;
	
	key_val = key_scan_btn();
	key_down = key_val & (key_old^key_val);
	key_up = ~key_val & (key_old^key_val);
	key_old = key_val;
	
	if(key_down == 4)
		seg_mode = (++seg_mode)%2;
	
	switch(key_down) {
		case 4:
			if(pwm_rate > 0)
				pwm_rate--;
		break;
		case 5:
			if(pwm_rate < 10)
				pwm_rate++;
		break;
	}

		
}

//============ISR==============
void timer0_init() {
	AUXR &= 0x7F;
	TMOD &= 0xF0;
	TL0 = 0x9C; //100us
	TH0 = 0xFF;
	TF0 = 0;
	TR0 = 1;
	ET0 = 1;
}

void isr_timer_0() interrupt 1 {
	//1KHz
	if(pwm_count < pwm_rate_led) {
		P34 = 1;
		led_code = 0x55;
	} else {
		P34 = 0;
		led_code = 0;
	}
	led_disp(led_code);
	if(++pwm_count == 100) pwm_count = 0;
}

void timer1_init() {
	AUXR &= 0xBF;
	TMOD &= 0x0F;
	TL1 = 0x18;	//1ms
	TH1 = 0xFC;	
	TF1 = 0;	
	TR1 = 1;
	ET1 = 1;
}

void isr_timer_1() interrupt 3 {
	timer_count++;
	
	//led_disp(led_code);
	seg_disp(seg_pos, seg_buf);
	if(++seg_pos == 8) seg_pos = 0;
}

//============MAIN==============
void main() {
	
	sys_init();
	timer0_init();
	timer1_init();
	EA = 1;
	
	while(1) {
		led_proc();
		seg_proc();
		key_proc();
		

	}
	
}

